//
//  CustomerNetWorking.m
//  B段_开眼
//
//  Created by hu on 16/4/21.
//  Copyright © 2016年 Howie. All rights reserved.
//

#import "CustomerNetWorking.h"


@implementation CustomerNetWorking


+ (void)connectWithURL:(NSString *)urlStr andUpdate:(BOOL)isUpdate andBlock:(void (^)(id response))block
{
    
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //    设置存储路劲
    NSString *fileStr = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    //    MD5简单加密
    NSString *filePath = [fileStr stringByAppendingPathComponent:[urlStr stringFromMD5Capital]];
    //    设置监听
    if (isUpdate) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/json", @"application/json", @"text/javascript", @"text/html", nil];
        manager.securityPolicy.allowInvalidCertificates = YES;
        [manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            block(responseObject);
            // 归档存储
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:responseObject];
            [data writeToFile:filePath atomically:YES];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@", error);
        }];
    } else {
        Reachability *reach = [Reachability reachabilityForInternetConnection];
        if (0 == reach.currentReachabilityStatus || [fileManager fileExistsAtPath:filePath]) {
            NSData *data = [NSData dataWithContentsOfFile:filePath];
            block([NSKeyedUnarchiver unarchiveObjectWithData:data]);
        } else {
            AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
            manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"text/json", @"application/json", @"text/javascript", @"text/html", nil];
            manager.securityPolicy.allowInvalidCertificates = YES;
            [manager GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                block(responseObject);
                // 归档存储
                NSData *data = [NSKeyedArchiver archivedDataWithRootObject:responseObject];
                [data writeToFile:filePath atomically:YES];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"%@", error);
            }];
        }
    }
}





@end
